package com.haierp.controller.purchase;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.imageio.ImageIO;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.haierp.dto.BuyerDTO;
import com.haierp.dto.BuyerTaskDailyDTO;
import com.haierp.enums.GeneralStatus;
import com.haierp.exception.ErpCommonException;
import com.haierp.mapper.TaskDailyDetailMapper;
import com.haierp.mapper.TaskDailyMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.ItemSku;
import com.haierp.model.TaskDaily;
import com.haierp.model.TaskDailyDetail;
import com.haierp.model.TaskDailyOrder;
import com.haierp.model.TaskDailyOrderUncomplete;
import com.haierp.model.WxPurchaseUser;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.ITaskDailyDetailService;
import com.haierp.service.ITaskDailyOrderService;
import com.haierp.service.ITaskDailyOrderUncompleteService;
import com.haierp.service.ITaskDailyService;
import com.haierp.service.purchase.IWxPurchaseUserService;
import com.haierp.util.DateUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.util.ExcelTool.ExcelHelper;
import com.haierp.vo.BuyerTaskVO;
import com.haierp.vo.ErpOrderQueryVO;
import com.haierp.vo.ItemSkuQueryVO;
import com.haierp.vo.PurchaseQueryVO;
import com.haierp.vo.TaskDailyOrderUncompleteQueryVO;
import com.haierp.vo.json.PicModel;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;
import com.wangzhixuan.model.User;
import com.wangzhixuan.service.IUserService;

@Controller
@RequestMapping("/purchase")
public class PurchaseController extends BaseController {

	
	@Autowired
	private ITaskDailyService iTaskDailyService;
	
	@Autowired
	private ITaskDailyDetailService taskDailyDetailService;
	
	@Autowired
	private IItemSkuService iItemSkuService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	
	@Autowired
	private ITaskDailyOrderService taskDailyOrderService;
	
	@Autowired
	private ITaskDailyOrderUncompleteService taskDailyOrderUncompleteService;
	
	@Autowired
	private IWxPurchaseUserService wxUserPurchaseService;
	
	@Autowired
	private IErpOrderService erpOrderService;
	
	@Autowired
	private TaskDailyMapper taskDailyMapper;
	
	@Autowired
	private TaskDailyDetailMapper taskDailyDetailMapper;
	/**
	 * 新增采购任务
	 * @param
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Object add(TaskDaily taskDaily) {
		JsonResult<String> result = new JsonResult<>();
		 ShiroUser su = null;
		try {
			 su = this.getShiroUser();
		} catch (Exception e) {
			e.printStackTrace();
			return result.buildIsSuccess(false).buildMsg("没有登入");
		}
		final Long loginId = su.getId();
		final String loginName = su.getName();
		//1,生成采购单号
		String taskOrderNo = "T" + DateUtil.formatDate(new Date(),DateUtil.DATE_PARTEN_YYMMDD) + "U" + String.format("%0"+4+"d", loginId) + sequenceUtilService.gainTASKSequence();
		taskDaily.setCompanyId(su.getCompanyId());//所属公司
		taskDaily.setTaskOrderNo(taskOrderNo);
		taskDaily.setGmtCreate(new Date());
		taskDaily.setGmtModify(new Date());
		taskDaily.setOwnerId(loginId);
		taskDaily.setOwnerName(loginName);
		taskDaily.setStatus(GeneralStatus.INIT.getCode());
		if(taskDaily.getBuyerId()!=null){
			User user = userService.selectById(taskDaily.getBuyerId());
			taskDaily.setBuyerName(user.getName());
			taskDaily.setBuyerId(user.getId());
		}
		taskDaily.setStatus(0);
		if(!StringUtils.isEmpty(taskDaily.getImageUrl())){
			String url = taskDaily.getImageUrl().replace("&quot;", "\"");
			taskDaily.setImageUrl(url);
		}
//		taskDaily.getTaskDetailList();
		if(!StringUtils.isEmpty(taskDaily.getDetailList())){
			
			String s = taskDaily.getDetailList().replace("&quot;", "\"");
			List<TaskDailyDetail> details = HaiJsonUtils.toBean(s, new TypeReference<List<TaskDailyDetail>>(){});
			details.forEach(
					detail->{
						if(detail.getSkuId()==null){
						  result.buildIsSuccess(false).buildMsg("没有sku id信息");
						}else{
							ItemSku is= iItemSkuService.selectById(detail.getSkuId());
							if(is==null){
								result.buildIsSuccess(false).buildMsg("查询不到sku信息");
							}else{
								detail.setUpc(is.getUpc());
								detail.setItemId(is.getItemId());
								detail.setSkuCode(is.getSkuCode());
								detail.setOwnerId(loginId);
								detail.setOwnerName(loginName);
								detail.setCompanyId(is.getCompanyId());
							}
						}
						String taskStartTimeStr = DateUtil.ymdFormat(taskDaily.getTaskStartTime());
						Date taskStartTime = DateUtil.parseDate(taskStartTimeStr + " 00:00:00");
						detail.setTaskStartTime(taskStartTime);
						String taskEndTimeStr = DateUtil.ymdFormat(taskDaily.getTaskEndTime());
						Date taskEndTime = DateUtil.parseDate(taskEndTimeStr + " 23:59:59");
						detail.setTaskEndTime(taskEndTime);
					}
			);
			taskDaily.setTaskDetailList(details);
		}
		iTaskDailyService.addTaskDaily(taskDaily);
		return result.buildIsSuccess(true);
	}
	
	
	/**
	 * 查询单个采购任务
	 * @param
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Object query(Long id) {
		JsonResult<TaskDaily> result = new JsonResult<>();
		if(id==null){
			return result.buildIsSuccess(false).buildMsg("id 不能为 null");
		}
		TaskDaily td = iTaskDailyService.query(id);
		return result.buildIsSuccess(true).buildData(td);
	}
	
	/**
	 * 更新采购任务
	 * @param
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Object update(TaskDaily taskDaily) {
		JsonResult<String> result = new JsonResult<>();
		 ShiroUser su = null;
		try {
			 su = this.getShiroUser();
		} catch (Exception e) {
			e.printStackTrace();
			return result.buildIsSuccess(false).buildMsg("没有登入");
		}
		final Long loginId = su.getId();
		final String loginName = su.getName();
		taskDaily.setGmtModify(new Date());
		taskDaily.setOwnerId(loginId);
		taskDaily.setOwnerName(loginName);
		taskDaily.setCompanyId(su.getCompanyId()); //修改采购单也加入companyId
		if(taskDaily.getBuyerId()!=null){
			User user = userService.selectById(taskDaily.getBuyerId());
			taskDaily.setBuyerName(user.getName());
			taskDaily.setBuyerId(user.getId());
		}
		if (taskDaily.getId() == null) {
			return result.buildIsSuccess(false).buildMsg("没有采购任务 id");
		} 
		if(!StringUtils.isEmpty(taskDaily.getImageUrl())){
			String url = taskDaily.getImageUrl().replace("&quot;", "\"");
			taskDaily.setImageUrl(url);
		}
		
		if(!StringUtils.isEmpty(taskDaily.getDetailList())){
			
			String s = taskDaily.getDetailList().replace("&quot;", "\"");
			List<TaskDailyDetail> details = HaiJsonUtils.toBean(s, new TypeReference<List<TaskDailyDetail>>(){});
			details.forEach(
				detail->{
						if(detail.getSkuId()==null){
						  result.buildIsSuccess(false).buildMsg("没有sku id信息");
						}else{
							ItemSku is= iItemSkuService.selectById(detail.getSkuId());
							if(is==null){
								result.buildIsSuccess(false).buildMsg("查询不到sku信息");
							}else{
								detail.setUpc(is.getUpc());
								detail.setItemId(is.getItemId());
								detail.setCompanyId(is.getCompanyId());//修改同时加入companyId
								detail.setSkuCode(is.getSkuCode());
								detail.setOwnerId(loginId);
								detail.setOwnerName(loginName);
							}
						}
						String taskStartTimeStr = DateUtil.ymdFormat(taskDaily.getTaskStartTime());
						Date taskStartTime = DateUtil.parseDate(taskStartTimeStr + " 00:00:00");
						detail.setTaskStartTime(taskStartTime);
						String taskEndTimeStr = DateUtil.ymdFormat(taskDaily.getTaskEndTime());
						Date taskEndTime = DateUtil.parseDate(taskEndTimeStr + " 23:59:59");
						detail.setTaskEndTime(taskEndTime);
					}
						
			);
			taskDaily.setTaskDetailList(details);
		}
		iTaskDailyService.updateTaskDaily(taskDaily);
		return result.buildIsSuccess(true);
	}
	
	@RequestMapping("/queryTaskDailyList")
	@ResponseBody
	public Object queryTaskDailyList(PurchaseQueryVO purchaseQueryVO) {
		JsonPageResult<List<TaskDaily>> result = new JsonPageResult<>();
		try{
			//如果是第三方买手
			ShiroUser shiroUser = this.getShiroUser();
			Set<String> roles = shiroUser.getRoles();
			if(roles.contains("irhbuyer")) {
				purchaseQueryVO.setBuyerId(shiroUser.getId());
			}

			result = iTaskDailyService.queryTaskDailyList(purchaseQueryVO);
			//只有最高权限才能看到常备采购任务
			List<TaskDaily> taskDailyList = result.getData();
			for(int i=0; i<taskDailyList.size(); i++) {
				if(taskDailyList.get(i).getIfStanding()==1 && !roles.contains("report")) {
					taskDailyList.remove(i);
					i--;
				}
			}

			if(roles.contains("irhbuyer")) {
				result.setAgentRoler(true);
			}
			if(roles.contains("noexport")) {
				result.setNoEexportRoler(true);
			}
			result.buildIsSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			result.buildIsSuccess(false);
		}
		return result;
	}
	
	@RequestMapping("/queryBuyers")
	@ResponseBody
	public Object queryBuyers() {
		JsonResult<List<BuyerDTO>> result = new JsonResult<>();
		try {
			EntityWrapper<WxPurchaseUser> wrapper = new EntityWrapper<WxPurchaseUser>();
			//如果是第三方买手
			ShiroUser shiroUser = this.getShiroUser();
			Set<String> roles = shiroUser.getRoles();
			if(roles.contains("irhbuyer")) {
				WxPurchaseUser tjWxPurchaseUser = new WxPurchaseUser();
				tjWxPurchaseUser.setId(shiroUser.getId());
				wrapper.setEntity(tjWxPurchaseUser);
			}
			List<WxPurchaseUser> users = wxUserPurchaseService.selectList(wrapper);
			if (users != null && !users.isEmpty()) {
				List<BuyerDTO> buyers = new ArrayList<BuyerDTO>();
				users.forEach(user -> {
					if(user.getIsValid()!=null && user.getIsValid()==1) {
						BuyerDTO bd = new BuyerDTO();
						bd.setId(user.getId());
						bd.setName(user.getNickName());
						buyers.add(bd);
					}
				});
				result.buildIsSuccess(true).buildData(buyers);
			}
			result.buildIsSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.buildIsSuccess(false);
		}
		return result;
		/*
		 * JsonResult<List<BuyerDTO>> result = new JsonResult<>(); try{
		 * List<User> users = userService.queryBuyer();
		 * if(users!=null&&!users.isEmpty()){ List<BuyerDTO> buyers = new
		 * ArrayList<BuyerDTO> (); users.forEach(user->{ BuyerDTO bd = new
		 * BuyerDTO(); bd.setId(user.getId()); bd.setName(user.getName());
		 * buyers.add(bd); }); result.buildIsSuccess(true).buildData(buyers); }
		 * result.buildIsSuccess(true); }catch(Exception e){
		 * e.printStackTrace(); result.buildIsSuccess(false); } return result;
		 */
	}
	
	/**
	 * 根据买手ID，查询所有的采购任务
	 */
	@RequestMapping("/queryBuyerTaskList")
	@ResponseBody
	public Object queryBuyerTaskList(BuyerTaskVO buyerTaskVO) {
		JsonResult<List<BuyerTaskDailyDTO>> result = new JsonResult<>();
		try {
			if (buyerTaskVO.getBuyerId() == null) {
				result.buildIsSuccess(false).buildMsg("买手ID为Null");
			}
			List<BuyerTaskDailyDTO> taskDetailList = taskDailyDetailService.queryBuyerTaskList(buyerTaskVO);
			result.setData(taskDetailList);
			result.buildIsSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.buildIsSuccess(false);
		}
		return result;
	}
	
	/**
	 * 根据采购单ID，删除采购任务
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(Long id) {
		JsonResult<String> result = new JsonResult<>();
		
		try{
			iTaskDailyService.deleteTaskDailyById(id);
			return result.buildIsSuccess(true);
		}catch(ErpCommonException e){
			return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
		}catch(Exception ex){
			return result.buildIsSuccess(false).buildMsg("未知异常");
		}
	}
	
	/**
	 * 根据采购单ID导出excel
	 * @param id
	 */
	@RequestMapping("/taskDailyExport")
    public ResponseEntity<byte[]> taskDailyExport(Long id) throws Exception {
    	List<List<Object>> rowDatas = new ArrayList<>();
    	List<ItemSku> itemSkuList = taskDailyDetailService.taskDailyExportByTaskId(id);
    	if(itemSkuList != null) {
    		int i=0;
    		for (ItemSku item : itemSkuList) {
    			List<Object> list = new ArrayList<>();
    			//序号
    			//list.add(++i);
    			//sku图片
    			String skuPic = item.getSkuPic();
    			if(StringUtil.isNotBlank(skuPic)) {
    				PicModel pm = HaiJsonUtils.toBean(skuPic, PicModel.class);
        			String imgSrc = pm.getPicList().get(0).getUrl();
        			String imgType = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
        			if(imgSrc.contains("aliyuncs.com")) {
        				imgSrc += "?x-oss-process=image/resize,m_lfit,h_100,w_100";
        			} else {
        				imgSrc = imgSrc.replaceAll("Resource", "Thumbnail");
        			}
        			//System.out.println(imgSrc);
        			URL url = new URL(imgSrc);
        			BufferedImage image = ImageIO.read(url);
        			ByteArrayOutputStream output = new ByteArrayOutputStream();
        	        ImageIO.write(image, imgType, output);
        	        output.flush();
        	        list.add(output.toByteArray());
        	        output.close();
    			} else {
    				list.add(null);
    			}
    			
    	        list.add(item.getItemName());	//商品名称
    	        list.add(item.getSkuCode());	//SKU代码
    	        list.add(item.getUpc());		//UPC
    	        //list.add(item.getBrand());	//品牌
    	        list.add(item.getColor());		//颜色
    	        list.add(item.getScale());		//尺码
    	        list.add(item.getBuySite());    //采购站点
    	        list.add(item.getBuySiteRemark());//采购站点备注
    	        list.add(item.getCount());		//采购数量
    	        list.add(item.getInCount());    //入库数量    	   
    	        list.add(item.getCostPrice());    //原价
    	        list.add(item.getDiscount());    //折扣率
    	        list.add(item.getPurchasePrice());  //折后价
    			rowDatas.add(list);
    		}
    	}
    	ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"商品图片", "商品名称", "SKU代码", "UPC", "颜色", "尺码", "采购站点", "采购站点备注", "采购数量", "入库数量", "原价", "折扣率", "折后价"};
    	Integer[] columnWidth = new Integer[]{15, 30, 25, 25, 15, 15, 15, 25, 15, 15, 15, 15, 15};
    	excelHelper.setTaskDailyToSheet("Erp Order", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "采购单_" + itemSkuList.get(0).getTaskOrderNo() + ".xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
        return filebyte;
    }

	/**
	 * 根据采购单ID导出excel
	 * @param
	 */
	@RequestMapping("/noCompleteExport")
    public ResponseEntity<byte[]> noCompleteExport(String currentlyDate) throws Exception {
    	List<List<Object>> rowDatas = new ArrayList<>();
    	List<TaskDailyOrderUncomplete> noCompleteTaskDailyList = taskDailyOrderUncompleteService.queryNocompleteTaskDaily(currentlyDate);
    	if(noCompleteTaskDailyList != null) {
    		int i=0;
    		for (TaskDailyOrderUncomplete noComplete : noCompleteTaskDailyList) {
    			List<Object> list = new ArrayList<>();
    			//序号
    			//list.add(++i);
    			//sku图片
    			String skuPic = noComplete.getSkuPic();
    			if(StringUtil.isNotBlank(skuPic)) {
    				PicModel pm = HaiJsonUtils.toBean(skuPic, PicModel.class);
        			String imgSrc = pm.getPicList().get(0).getUrl();
        			String imgType = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
        			if(imgSrc.contains("aliyuncs.com")) {
        				imgSrc += "?x-oss-process=image/resize,m_lfit,h_100,w_100";
        			} else {
        				imgSrc = imgSrc.replaceAll("Resource", "Thumbnail");
        			}
        			//System.out.println(imgSrc);
        			URL url = new URL(imgSrc);
        			BufferedImage image = ImageIO.read(url);
        			ByteArrayOutputStream output = new ByteArrayOutputStream();
        	        ImageIO.write(image, imgType, output);
        	        output.flush();
        	        list.add(output.toByteArray());
        	        output.close();
    			} else {
    				list.add(null);
    			}
    			
    	        list.add(noComplete.getItemName());	//商品名称
    	        list.add(noComplete.getSkuCode());	//SKU代码
    	        list.add(noComplete.getUpc());		//UPC
    	        list.add(noComplete.getColor());		//颜色
    	        list.add(noComplete.getScale());		//尺码
    	        list.add(noComplete.getBuySite());    //采购站点
    	        list.add(noComplete.getPurchaseNeed());		//未完成采购数量
       
    			rowDatas.add(list);
    		}
    	}
    	ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"商品图片", "商品名称", "SKU代码", "UPC", "颜色", "规格", "采购站点", "未完成采购数量"};
    	Integer[] columnWidth = new Integer[]{15, 50, 25, 25, 15, 15, 20, 15};
    	excelHelper.setNoCompleteTaskDailyToSheet("NoComplete", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "未完成采购单("+currentlyDate+").xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
        return filebyte;
    }
    
    /**
     * 新增采购单添加商品，根据商品skuCode或者名称搜索
     * @param itemSkuQueryVO
     * @return
     */
    @RequestMapping("/queryItemSkuList")
	@ResponseBody
	public Object queryItemSkus(ItemSkuQueryVO itemSkuQueryVO) {
		JsonPageResult<List<ItemSku>> result = new JsonPageResult<>();
		try{
			itemSkuQueryVO.setIsPurchase(1);
			//按商品查询
			if(itemSkuQueryVO.getIsOrderQuery()==null || itemSkuQueryVO.getIsOrderQuery()!=1) {
				result = iItemSkuService.queryItemSkus(itemSkuQueryVO);
				List<ItemSku> itemSkuList = result.getData();
				if(itemSkuList!=null && itemSkuList.size()>0) {
					itemSkuList.forEach((itemSku)-> {
						String itemSkuCase = itemSku.getTaskDailyItemSkuCase();
						if(StringUtil.isNotBlank(itemSkuCase)) {
							String[] invArray = itemSkuCase.split(",");
							itemSku.setSaleNeed(Integer.parseInt(invArray[0]));			//订单所需数量
							itemSku.setPurchaseNeed(Integer.parseInt(invArray[1]));		//订单所需数量-仓库实际库存-在途库存
							itemSku.setInventory(Integer.parseInt(invArray[2]));		//现货库存
							itemSku.setTransInv(Integer.parseInt(invArray[3]));			//在途库存
							itemSku.setVirtualInv(Integer.parseInt(invArray[4]));		//虚拟库存
							itemSku.setLockedInv(Integer.parseInt(invArray[5]));		//现货占用
							itemSku.setLockedTransInv(Integer.parseInt(invArray[6]));	//在途占用
						}
					});
				}
			} else if(itemSkuQueryVO.getIsOrderQuery()!=null && itemSkuQueryVO.getIsOrderQuery()==1) {	//按订单查询
				Map<Long, Integer> taskBuyedMap = new HashMap<Long, Integer>();
				BuyerTaskVO buyerTaskVO = new BuyerTaskVO();
				List<BuyerTaskDailyDTO> taskDetailList = taskDailyDetailService.queryBuyerTaskList(buyerTaskVO);
				taskDetailList.forEach(buyerTaskDailyDTO -> {
					Integer count = taskBuyedMap.get(buyerTaskDailyDTO.getSkuId());
					if(count != null) {
						taskBuyedMap.put(buyerTaskDailyDTO.getSkuId(), count+buyerTaskDailyDTO.getCount());
					} else {
						taskBuyedMap.put(buyerTaskDailyDTO.getSkuId(), buyerTaskDailyDTO.getCount());
					}
				});
				
				result = taskDailyOrderService.queryItemSkus(itemSkuQueryVO);
				List<ItemSku> itemSkuList = result.getData();
				for(int i=0; i<itemSkuList.size(); i++) {
					ItemSku itemSku = itemSkuList.get(i);
					Integer count = taskBuyedMap.get(itemSku.getId());
					if(count != null) {
						int purchaseNeed = itemSku.getPurchaseNeed() - count;
						if(purchaseNeed <= 0) {
							itemSku.setPurchaseNeed(0);
							itemSkuList.remove(i);
							i--;
							continue;
						} else {
							itemSku.setPurchaseNeed(purchaseNeed);
						}
					}
				}
			}
			result.buildIsSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			result.buildIsSuccess(false);
		}
		return result;
	}
    
    /**
     * 根据当前的销售订单以及库存情况，产生采购明细
     * @return
     */
    @RequestMapping("/createTaskDailyOrder")
	@ResponseBody
	public Object createTaskDailyOrder() {
    	JsonResult<String> result = new JsonResult<>();
    	try {
    		taskDailyOrderService.createTaskDailyOrder();
    		return result.buildIsSuccess(true);
    	} catch(Exception e) {
    		return result.buildIsSuccess(false).buildMsg("未知异常");
    	}
    }
    
    /**
     * 取消采购
     * @return
     */
    @RequestMapping("/closeTaskDaily")
	@ResponseBody
	public Object closeTaskDaily(String taskDailyIds) {
    	JsonResult<String> result = new JsonResult<>();
    	if(StringUtil.isBlank(taskDailyIds)) {
    		return result.buildIsSuccess(false).buildMsg("未选中采购任务");
    	}
    	String s = taskDailyIds.replace("&quot;", "\"");
		List<Long> taskDailyIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		try {
			iTaskDailyService.closeTaskDaily(taskDailyIdList);
			return result.buildIsSuccess(true);
		} catch(Exception ex) {
			return result.buildIsSuccess(false).buildMsg("未知异常");
		}
    }
    
    /**
     * 完成采购
     * @return
     */
    @RequestMapping("/finishTaskDaily")
	@ResponseBody
	public Object finishTaskDaily(String taskDailyIds) {
    	JsonResult<String> result = new JsonResult<>();
    	if(StringUtil.isBlank(taskDailyIds)) {
    		return result.buildIsSuccess(false).buildMsg("未选中采购任务");
    	}
    	String s = taskDailyIds.replace("&quot;", "\"");
		List<Long> taskDailyIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		try {
			iTaskDailyService.finishTaskDaily(taskDailyIdList);
			return result.buildIsSuccess(true);
		} catch(Exception ex) {
			ex.printStackTrace();
			return result.buildIsSuccess(false).buildMsg("未知异常");
		}
    }
    
    /**
	 * 根据当前订单生成采购单
	 * @param
	 * @return
	 */
	@RequestMapping("/autoAddByOrder")
	@ResponseBody
	public Object autoAddByOrder(TaskDaily taskDaily) {
		JsonResult<String> result = new JsonResult<>();
		//根据当前的销售订单以及库存情况，产生采购明细
		taskDailyOrderService.createTaskDailyOrder();
		
		ShiroUser su = null;
		try {
			 su = this.getShiroUser();
		} catch (Exception e) {
			e.printStackTrace();
			return result.buildIsSuccess(false).buildMsg("没有登入");
		}
		final Long loginId = su.getId();
		final String loginName = su.getName();
		//1,生成采购单号
		String taskOrderNo = "T" + DateUtil.formatDate(new Date(),DateUtil.DATE_PARTEN_YYMMDD) + "U" + String.format("%0"+4+"d", loginId) + sequenceUtilService.gainTASKSequence();
		taskDaily.setTaskOrderNo(taskOrderNo);
		taskDaily.setCompanyId(su.getCompanyId());//采购明细加入公司ID
		taskDaily.setGmtCreate(new Date());
		taskDaily.setGmtModify(new Date());
		taskDaily.setOwnerId(loginId);
		taskDaily.setOwnerName(loginName);
		taskDaily.setStatus(GeneralStatus.INIT.getCode());
		taskDaily.setBuyerName("Daniel");
		taskDaily.setBuyerId(16L);
		taskDaily.setTaskTitle("订单采购");
		taskDaily.setTaskDesc("根据当前销售订单产生采购任务");
		taskDaily.setIfStanding(0);
		taskDaily.setImageUrl("{\"picList\":[]}");
		
		//时间
		String taskStartTimeStr = DateUtil.ymdFormat(new Date());
		Date taskStartTime = DateUtil.parseDate(taskStartTimeStr + " 00:00:00");
		String taskEndTimeStr = DateUtil.ymdFormat(new Date());
		Date taskEndTime = DateUtil.parseDate(taskEndTimeStr + " 23:59:59");
		
		taskDaily.setTaskStartTime(taskStartTime);
		taskDaily.setTaskEndTime(taskStartTime);
		
		//查看当前有效的采购任务
		Map<Long, Integer> taskBuyedMap = new HashMap<Long, Integer>();
		BuyerTaskVO buyerTaskVO = new BuyerTaskVO();
		List<BuyerTaskDailyDTO> taskDetailList = taskDailyDetailService.queryBuyerTaskList(buyerTaskVO);
		taskDetailList.forEach(buyerTaskDailyDTO -> {
			Integer count = taskBuyedMap.get(buyerTaskDailyDTO.getSkuId());
			if(count != null) {
				taskBuyedMap.put(buyerTaskDailyDTO.getSkuId(), count+buyerTaskDailyDTO.getCount());
			} else {
				taskBuyedMap.put(buyerTaskDailyDTO.getSkuId(), buyerTaskDailyDTO.getCount());
			}
		});
		
		//明细
		List<TaskDailyOrder> taskDailyOrderList = taskDailyOrderService.queryAll();
		if(!StringUtils.isEmpty(taskDailyOrderList)) {
			List<TaskDailyDetail> taskDailyDetailList = new ArrayList<TaskDailyDetail>();
			taskDailyOrderList.forEach(
					taskDailyOrder -> {
						if(taskDailyOrder.getPurchaseNeed()!=null && taskDailyOrder.getPurchaseNeed()>0) {
							TaskDailyDetail taskDailyDetail = new TaskDailyDetail();
							taskDailyDetail.setItemId(taskDailyOrder.getItemId());
							taskDailyDetail.setSkuId(taskDailyOrder.getSkuId());
							taskDailyDetail.setUpc(taskDailyOrder.getUpc());
							taskDailyDetail.setSkuCode(taskDailyOrder.getSkuCode());
							taskDailyDetail.setOwnerName("admin");
							taskDailyDetail.setOwnerId(1L);
							taskDailyDetail.setBuyerId(16L);
							taskDailyDetail.setTaskStartTime(taskStartTime);
							taskDailyDetail.setTaskEndTime(taskEndTime);
							taskDailyDetail.setMode(1);
							taskDailyDetail.setRemark("0");
							
							Integer count = taskBuyedMap.get(taskDailyOrder.getSkuId());
							if(count != null) {
								int purchaseNeed = taskDailyOrder.getPurchaseNeed() - count;
								if(purchaseNeed < 0) {
									taskDailyDetail.setCount(0);
								} else {
									taskDailyDetail.setCount(purchaseNeed);
								}
							} else {
								taskDailyDetail.setCount(taskDailyOrder.getPurchaseNeed());
							}
							
							if(taskDailyDetail.getCount() > 0) {
								taskDailyDetailList.add(taskDailyDetail);
							}
						}
					}
			);
			if(taskDailyDetailList.size() == 0) {
				return result.buildIsSuccess(false).buildMsg("没有新增订单产生采购任务");
			}
			taskDaily.setTaskDetailList(taskDailyDetailList);
			iTaskDailyService.addTaskDaily(taskDaily);
		}
		return result.buildIsSuccess(true);
	}
	
    /**
	 * 未完成采购时间
	 * @param
	 * @return
	 */
	@RequestMapping("/nocompleteTaskDailyOrderTime")
	@ResponseBody
	public Object NocompleteTaskDailyOrderTime(TaskDailyOrderUncompleteQueryVO taskDailyOrderUncompleteQueryVO){
		JsonPageResult<List<TaskDailyOrderUncomplete>> result = new JsonPageResult<>();
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		result = taskDailyOrderUncompleteService.queryNocomplete(taskDailyOrderUncompleteQueryVO);
		if(roles.contains("noexport")) {
			result.setNoEexportRoler(true);
		}
		return result.buildIsSuccess(true);
	}
	
	/**
	 * 未完成采购详情
	 * @param
	 * @return
	 */
	@RequestMapping("/nocompleteTaskDaily")
	@ResponseBody
	public Object NocompleteTaskDaily(String currentlyDate){
		JsonResult<List<TaskDailyOrderUncomplete>> result = new JsonResult<>();
		List<TaskDailyOrderUncomplete> queryNocompleteTaskDaily = taskDailyOrderUncompleteService.queryNocompleteTaskDaily(currentlyDate);
		return result.buildIsSuccess(true).buildData(queryNocompleteTaskDaily);
	}
	
	/**
	 * 未备货订单和sku
	 * @param erpOrderQueryVO
	 * @return
	 */
	@RequestMapping("/queryNoStockSku")
	@ResponseBody
	public Object query(ErpOrderQueryVO erpOrderQueryVO) {
		JsonPageResult<List<ErpOrder>> result = new JsonPageResult<>();
		result = erpOrderService.queryOrderNoStockSku(erpOrderQueryVO);
		result.setSuccess(true);
		return result;
	}
	/**
	 * 操作erp退单
	 * @param erpOrderQueryVO
	 * @param erpIds
	 * @return
	 */
	@RequestMapping("/addReturnErpOrderIds")
	@ResponseBody
	public Object addFile(ErpOrderQueryVO erpOrderQueryVO,String erpIds){
		JsonResult<String> result = new JsonResult<>();
		if(!StringUtils.isEmpty(erpIds)){
			String s = erpIds.replace("&quot;", "\"");
			List<Long> idList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
			if(CollectionUtils.isNotEmpty(idList)){
				List<ErpOrder> erpOrders = erpOrderService.selectBatchIds(idList);
				for (ErpOrder erpOrder : erpOrders) {
			         if(erpOrder.getRemark()!= null){
							erpOrder.setRemark(erpOrder.getRemark()+" /  采购SKU备注："+erpOrderQueryVO.getPurchaseRemark());
			         }else{
					        erpOrder.setRemark("采购SKU备注："+ erpOrderQueryVO.getPurchaseRemark()); 
			         }
					erpOrder.setPurchaseStatus(1);
					erpOrderService.updateSelectiveById(erpOrder);
				}
			}
		}
		return result.buildIsSuccess(true);
	}
	
    /**
     * 根据采购站点run出采购单
     * @return
     */
	@RequestMapping("/autoAddBySites")
	@ResponseBody
	public Object autoAddBySites() {
		JsonResult<String> result = new JsonResult<>();
		
		//根据当前的销售订单以及库存情况，产生采购明细
		taskDailyOrderService.createTaskDailyOrder();
		
		//查看当前有效的采购任务
		Map<Long, Integer> taskBuyedMap = new HashMap<Long, Integer>();
		BuyerTaskVO buyerTaskVO = new BuyerTaskVO();
		List<BuyerTaskDailyDTO> taskDetailList = taskDailyDetailService.queryBuyerTaskList(buyerTaskVO);
		taskDetailList.forEach(buyerTaskDailyDTO -> {
			Integer count = taskBuyedMap.get(buyerTaskDailyDTO.getSkuId());
			if(count != null) {
				taskBuyedMap.put(buyerTaskDailyDTO.getSkuId(), count+buyerTaskDailyDTO.getCount());
			} else {
				taskBuyedMap.put(buyerTaskDailyDTO.getSkuId(), buyerTaskDailyDTO.getCount());
			}
		});
		
		//时间
		String taskStartTimeStr = DateUtil.ymdFormat(new Date());
		Date taskStartTime = DateUtil.parseDate(taskStartTimeStr + " 00:00:00");
		String taskEndTimeStr = DateUtil.ymdFormat(new Date());
		Date taskEndTime = DateUtil.parseDate(taskEndTimeStr + " 23:59:59");
		
		//明细
		List<TaskDailyOrder> taskDailyOrderList = taskDailyOrderService.queryAll();
		Map<String, List<TaskDailyDetail>> taskDailyDetailMap = new CaseInsensitiveMap();//map 忽略大小写方法
		if(!StringUtils.isEmpty(taskDailyOrderList)) {
			taskDailyOrderList.forEach(
					taskDailyOrder -> {
						if(taskDailyOrder.getPurchaseNeed()!=null && taskDailyOrder.getPurchaseNeed()>0) {
							TaskDailyDetail taskDailyDetail = new TaskDailyDetail();
							taskDailyDetail.setItemId(taskDailyOrder.getItemId());
							taskDailyDetail.setSkuId(taskDailyOrder.getSkuId());
							taskDailyDetail.setUpc(taskDailyOrder.getUpc());
							taskDailyDetail.setSkuCode(taskDailyOrder.getSkuCode());
							taskDailyDetail.setOwnerName("admin");
							taskDailyDetail.setOwnerId(1L);
							taskDailyDetail.setBuyerId(16L);
							taskDailyDetail.setTaskStartTime(taskStartTime);
							taskDailyDetail.setTaskEndTime(taskEndTime);
							taskDailyDetail.setMode(1);
							taskDailyDetail.setRemark("0");
							
							Integer count = taskBuyedMap.get(taskDailyOrder.getSkuId());
							if(count != null) {
								int purchaseNeed = taskDailyOrder.getPurchaseNeed() - count;
								if(purchaseNeed < 0) {
									taskDailyDetail.setCount(0);
								} else {
									taskDailyDetail.setCount(purchaseNeed);
								}
							} else {
								taskDailyDetail.setCount(taskDailyOrder.getPurchaseNeed());
							}
							
							String buySite = taskDailyOrder.getBuySite();
							if(StringUtil.isBlank(buySite)) {
								buySite = "none";
							}
							List<TaskDailyDetail> taskDailyDetailList = taskDailyDetailMap.get(buySite);
							if(taskDailyDetailList == null) {
								taskDailyDetailList = new ArrayList<TaskDailyDetail>();
								taskDailyDetailMap.put(buySite, taskDailyDetailList);
							}
							if(taskDailyDetail.getCount() > 0) {
								taskDailyDetailList.add(taskDailyDetail);
							}
						}
					}
			);
		} else {
			return result.buildIsSuccess(false).buildMsg("没有新增订单产生采购任务");
		}
		
		
		ShiroUser one = this.getShiroUser();
		final Long loginId = one.getId();
		final String loginName = one.getName();
		
		TreeMap<String, List<TaskDailyDetail>> treeMap = new TreeMap<String, List<TaskDailyDetail>>(new Comparator<String>(){
			public int compare(String a,String b){  
                return b.compareTo(a);     
            }  
		});
		for (String string : taskDailyDetailMap.keySet()) {
			treeMap.put(string, taskDailyDetailMap.get(string));
		}
		
		boolean isHasOrder = false;
		for (String string : treeMap.keySet()) {
			List<TaskDailyDetail> details = treeMap.get(string);
			if(CollectionUtils.isNotEmpty(details)) {
				TaskDaily taskDaily = new TaskDaily();
				//1,生成采购单号
				String taskOrderNo = "T" + DateUtil.formatDate(new Date(),DateUtil.DATE_PARTEN_YYMMDD) + "U" + String.format("%0"+4+"d", loginId) + sequenceUtilService.gainTASKSequence();
				taskDaily.setTaskOrderNo(taskOrderNo);
				taskDaily.setCompanyId(one.getCompanyId());//采购明细加入公司ID
				taskDaily.setGmtCreate(new Date());
				taskDaily.setGmtModify(new Date());
				taskDaily.setOwnerId(loginId);
				taskDaily.setOwnerName(loginName);
				taskDaily.setStatus(GeneralStatus.INIT.getCode());
				taskDaily.setBuyerName("Daniel");
				taskDaily.setBuyerId(16L);
				if("none".equals(string)) {
					taskDaily.setTaskTitle("站点暂无");
					taskDaily.setTaskDesc("站点暂无");
				}else{
					taskDaily.setTaskTitle(string);
					taskDaily.setTaskDesc(string);	
				}
				taskDaily.setImageUrl("{\"picList\":[]}");
				//时间
				taskDaily.setTaskStartTime(taskStartTime);
				taskDaily.setTaskEndTime(taskStartTime);	//注意这里的时间，由于历史原因，采购单的开始时间和结束时间需要一致，否则会引起定时任务不能取消，从而导致task_daily_order在凌晨数据不会刷新
				taskDaily.setTaskDetailList(details);
				taskDaily.setIfStanding(0);					//非常备采购
				iTaskDailyService.addTaskDaily(taskDaily);
				isHasOrder = true;
			}
		}
		if(!isHasOrder) {
			return result.buildIsSuccess(false).buildMsg("没有新增订单产生采购任务");
		}
		return result.buildIsSuccess(true);
	}
}
